package com.drugStorage.hibernate.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.drugStorage.domain.Department;
import com.drugStorage.hibernate.Utils.HibernateUtils;
import com.drugStorage.hibernate.dao.DepartmentDao;

public class DepartmentDaoImpl implements DepartmentDao {

	private static final String LOADS_ALL = "from Department";

	public void delDepartment(Department department) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtils.getSession();
			tx = s.beginTransaction();
			s.delete(department);
			tx.commit();
		} finally {
			if (s != null)
				s.close();

		}

	}

	public Department getDepartment(int id) {
		Session s = null;

		try {
			s = HibernateUtils.getSession();

			Criteria c = s.createCriteria(Department.class);
			c.add(Restrictions.eq("id", id));
			Department department = (Department) c.uniqueResult();
			return department;

		} finally {
			if (s != null)
				s.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Department> getDepartments() {
		Session s = null;
		try {
			s = HibernateUtils.getSession();
			Query q = s.createQuery(LOADS_ALL);

			return q.list();

		} finally {
			if (s != null)
				s.close();

		}

	}

	public void saveDepartment(Department department) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtils.getSession();
			tx = s.beginTransaction();
			s.persist(department);
			tx.commit();
		} finally {
			if (s != null)
				s.close();

		}

	}

	public void updateDepartment(Department department) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtils.getSession();
			tx = s.beginTransaction();
			s.saveOrUpdate(department);
			tx.commit();
		} finally {
			if (s != null)
				s.close();

		}

	}

}
